-- BackBag
--背包

BackBag = class()
BackBag.width = 9
BackBag.height = 9
BackBag.count = BackBag.width * BackBag.height

function BackBag:init()
    self.width = BackBag.width
    self.height = BackBag.height
    self.open = false
    self.posX = 1
    self.posY = 1
    self.items = {}
    
    for k,v in pairs(Object.objects) do
        if v.backBagPosition then
            self:setItem(v.backBagPosition.x,v.backBagPosition.y,v)
        end
    end
end

function BackBag:draw()
    if self.open == true then
        for xa = 1,self.width do
            for ya = 1,self.height do
                sprite("Project:seletorA",100+80*xa,5+80*ya,75,75)
            end
        end
        pushStyle()
        tint(41, 41, 41, 255)
        sprite("Project:seletorA",100+80*self.posX,5+80*self.posY,75,75)
        popStyle()
        for k,v in pairs(self.items) do
            sprite(v.item.icon,100+80*v.posX,5+80*v.posY,50,50)
        end
    end
end

function BackBag:touched(touch)
    if self.open then
        for x = 1,self.width do
            for y = 1,self.height do
                if self:isTouchInPos(touch,x,y) then
                    self.posX = x
                    self.posY = y
                    if touch.state == ENDED then
                        local item = self:getItem(self.posX,self.posY)
                        if item then
                            game.gui.bar:setItem(game.gui.bar.pos,item)
                        end
                    end
                    return true
                end
            end
        end
    end
    return false
end

function BackBag:isTouchInPos(touch,posX,posY)
    return touch.x > math.abs((100 + 80 * posX) - 40) and touch.x<math.abs((100 + 80 * posX) + 40) and touch.y > math.abs((5 + 80 * posY) - 40) and touch.y < math.abs((5 + 80 * posY) + 40)
end

function BackBag:setItem(x,y,object)
    if self:getItem(x,y) then
        for k,v in pairs(self.items) do
            if v.posX == x and v.posY == y then
                v.item = object
                return
            end
        end
    else
        table.insert(self.items,{posX = x,posY = y,item = object})
    end
end

function BackBag:getItem(x,y)
    for k,v in pairs(self.items) do
        if v.posX == x and v.posY == y then
            return v.item
        end
    end
    return nil
end

function BackBag:changeState()
    self.open = not self.open
end
